import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;

import com.delphi.tcde.plug.editor.GraphEditor;
import com.delphi.tcde.plug.model.Graph;
import com.delphi.tcde.plug.model.io.GraphReader;


public class LoadFromFile implements IWorkbenchWindowActionDelegate {

	@Override
	public void run(IAction action) {
		GraphEditor.cret();
	//	openFile();
		// TODO Auto-generated method stub

	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		// TODO Auto-generated method stub

	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(IWorkbenchWindow window) {
		// TODO Auto-generated method stub

	}
	
    private void openFile() {
        Shell shell = Display.getDefault().getActiveShell();
        FileDialog dialog = new FileDialog(shell, SWT.OPEN);
        dialog.setText("Select a Genealogy Graph File");
        String path = dialog.open();
        if (path == null)
        return;
        try {
        readAndClose(new FileInputStream(path));
        }
        catch (FileNotFoundException e) {
        e.printStackTrace();
        }
        }
    
    private void readAndClose(InputStream stream) {
        Graph newGraph = new Graph();
        try {
        new GraphReader(newGraph).read(stream);
        }
        catch (Exception e) {
        e.printStackTrace();
        return;
        }
        finally {
        try {
        stream.close();
        }
        catch (IOException e) {
        e.printStackTrace();
        }
        }
        GraphEditor.loadFileGraph(newGraph);
        }
   

}
